//
//  UITextView+Emoticon.swift
//  Emoticon
//
//  Created by 刘俊 on 15/10/28.
//  Copyright © 2015年 刘俊. All rights reserved.
//

import UIKit

extension UITextView {

    /// 文本视图中输入的图片表情完整字符串内容
    var emoticonText: String {

        let attrText = attributedText
        var strM = String()
        
        // 遍历属性文本
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? SYLJEmoticonAttachment {
                strM += attachment.emoticon.chs ?? ""
            } else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }

    /// 插入表情符号
    ///
    /// - parameter em: 表情模型
    func insertEmoticon(em: Emoticon) {
        //1, 插入空白表情
        if em.isEmpty {
            return
        }
        //2,插入删除按钮
        if em.isRemove {
            deleteBackward()
            return
        }
        //3,emoji
        if let emoji = em.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        //4,图片表情
        insertImageEmoticon(em)
        
    }
    
    /// 插入图片表情
    private func insertImageEmoticon(em: Emoticon) {
        
        let strM = SYLJEmoticonAttachment(emoticon: em).imageText(font!)
        //将文本属性转换为可变文本属性
        let imageText = NSMutableAttributedString(attributedString: attributedText)
        //插入图片文本
        imageText.replaceCharactersInRange(selectedRange, withAttributedString: strM)
        //记住'光标'的位置
        let range = selectedRange
        attributedText = imageText
        //恢复光标的位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}
